import { useCallback, useEffect, useMemo, useState } from 'react'
import { Select, SelectProps } from 'antd'

import { useControllerRef } from '@/hooks/useAbortController'
import { apiGetZoneList, zoneListRes } from './api'

export interface TimeZoneSelectProps extends Omit<SelectProps, 'options'> {
  /** 自定义 label 渲染（可选） */
  labelRenderer?: (item: zoneListRes) => React.ReactNode
}

/**
 * TimeZoneSelect
 * - 可用于 Form.Item 的受控组件（支持 value/onChange）
 * - 自动拉取时区列表
 */
export const TimeZoneSelect = (props: TimeZoneSelectProps) => {
  const { labelRenderer, ...rest } = props
  const [loading, setLoading] = useState(false)
  const [options, setOptions] = useState<SelectProps['options']>([])
  const controllerRef = useControllerRef()

  const toLabel = useCallback(
    (item: zoneListRes): React.ReactNode => {
      if (labelRenderer) return labelRenderer(item)
      const region = item.regions || ''
      const offset = item.utcOffset ? ` (${item.utcOffset})` : ''
      return `${region}${offset}`
    },
    [labelRenderer],
  )

  const toOption = useCallback(
    (item: zoneListRes) => ({
      label: item.utcOffset,
      value: item.utcOffset || '',
      key: item.utcOffset || '',
      item,
    }),
    [toLabel],
  )

  const fetchList = useCallback(async () => {
    setLoading(true)
    try {
      const data = await apiGetZoneList(controllerRef.current.signal)
      const sorted = (data || []).slice().sort((a, b) => (a.regions || '').localeCompare(b.regions || ''))
      setOptions(sorted.map(toOption))
    } finally {
      setLoading(false)
    }
  }, [toOption, controllerRef])

  useEffect(() => {
    fetchList()
  }, [fetchList])

  const filterOption = useMemo(() => {
    return (input: string, option?: { label?: React.ReactNode }) => {
      const labelText = String(option?.label ?? '')
      return labelText.toLowerCase().includes(input.toLowerCase())
    }
  }, [])

  return (
    <Select
      {...rest}
      options={options}
      loading={loading}
      showSearch
      placeholder="请选择时区"
      optionFilterProp="label"
      filterOption={filterOption}
      allowClear={rest.allowClear ?? true}
    />
  )
}

export default TimeZoneSelect
